package com.zhang;

import com.zhang.constant.Constant;
import com.zhang.core.DownloadTask;
import com.zhang.core.Downloader;
import com.zhang.util.HttpUtils;
import com.zhang.util.LogUtils;

import javax.xml.crypto.Data;
import java.io.*;
import java.util.Date;
import java.util.concurrent.FutureTask;

public class Test {

    public File file;
    public static void main(String[] args) throws IOException {
      /*  String url = "https://dldir1.qq.com/qqfile/qq/PCQQ9.7.1/QQ9.7.1.28940.exe";

       //FutureTask futureTask = new FutureTask( new DownloadTask(url, 0L, 10000L));
        Thread t = new Thread();
        t.start();
*/
       /* File file = new File("C:\\Users\\Admin\\Desktop\\test.jpg");
        long fileLength = file.length();
        long size = fileLength / 5;
        long startPos ;
        long endPos;
        for (int j = 0; j <5; j++) {
                startPos = j * size;

                if (j == Constant.THREAD_NUM - 1) {
                    //最后一块
                    endPos = 0;
                }else {
                    endPos = (j + 1) * size - 1;
                }
            System.out.println("开始：" + startPos + " || " + "结束：" + endPos);
        }*/
        //文件合并
        String s = "https://dldir1.qq.com/qqfile/qq/PCQQ9.7.1/QQ9.7.1.28940.exe";
        /*Downloader downloader = new Downloader();
        downloader.fileMerge(s);*/
        fileMerge(s);

    }

    private static void fileMerge(String url) {
        String filePath = null;
        String fileName = HttpUtils.getHttpFileName(url);
        filePath = Constant.PATH + fileName;
        for (int i = 0; i < Constant.THREAD_NUM; i++) {
            LogUtils.info("尝试写入块{}", i);

            File file = new File(Constant.PATH + fileName + ".temp" + i);

            try (       //获取输入流
                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    FileOutputStream fos = new FileOutputStream(filePath, true);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    ){
                int length = -1 ;
                byte[] bytes = new byte[Constant.BYTE_SIZE];
                while ((length = bis.read(bytes)) != -1) {
                      bos.write(bytes,0,length);
                    //bos.write(length);
                }
            } catch (IOException e) {
                LogUtils.error("发生未知错误");
                e.printStackTrace();
            }
            LogUtils.info("成功写入块{}", i);
        }
        LogUtils.info("合并完成！！！");
    }

}
